package sc;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

import sc.math.SimplexNoise;

public final class ProceduralTextures extends JFrame {

	private static final long serialVersionUID = 1L;

	/** Constructs an instance of ProceduralTextures */
    public ProceduralTextures(int width, int height) {
        setSize(width, height);
        setTitle("Procedural Textures");
        setResizable(false);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        setVisible(true);
    }
    
	/** Program entrypoint */
	public static void main(String[] args) {
		final int width = 640;
		final int halfwidth = width / 2;
		final int height = 480;
		final int halfheight = height / 2;
		
		// Create the JFrame application
		ProceduralTextures p = new ProceduralTextures(width, height);
		
		// Create a buffer strategry and graphics context
		p.createBufferStrategy(2);
        BufferStrategy s = p.getBufferStrategy();
        Graphics2D g;

		// Create a BufferedImage to paint noise on
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		int i = 100;
		
		// Main loop repeats while JFrame is visible
        while (p.isVisible()) {
            // Paint noise
           	for (int y = 0; y < height; y++) {
           		for (int x = 0; x < width; x++) {
           			double noise = SimplexNoise.noise(((x-halfwidth)/width) * i, ((y-halfheight)/height) * i, 0);
           			int shade = (int) ((noise + 1) * 128);
           			shade = (shade << 16) + (shade << 8) + shade;
           			img.setRGB(x, y, shade);
           		}
           	}
           	
            // Get the off screen graphics context
            g = (Graphics2D) s.getDrawGraphics();
           	
           	// Paint image to graphic context
           	g.drawImage(img, null, 0, 0);
           	
            // Swap the buffers
            s.show();
            
            i--;
        }
	}

}
